from django.shortcuts import render
from django.views.generic import View
from django.core.cache import cache
from django_redis import get_redis_connection
from django.shortcuts import render,redirect
from django.http import JsonResponse
from django.urls import reverse
from order.models import OrderGoods
from django.core.paginator import Paginator
from goods.models import *
from user.models import Address
from order.models import *
from datetime import datetime
from django.db import transaction
from alipay import AliPay ,ISVAliPay
import os
from dailyfresh import settings
# Create your views here.
class order_place(View):
    
    def post(self,request):
        data=request.POST
        sku_ids=data.getlist('goods')
        user=request.user
        if user.is_authenticated:
            con=get_redis_connection('default')
            user_key="cart_{}".format(user.id)
            content=[]
            for good_id in sku_ids:
                try:
                    good=GoodsSKU.objects.get(id=good_id)
                except GoodsSKU.DoesNotExist:
                    redirect(reverse("goods:index"))
                num=con.hget(user_key,good_id)
                content.append({'good':good,'num':num})
            
            addr=Address.objects.filter(user=user,is_default=False)[0:4]
            try:
                default_addr=Address.objects.get(user=user,is_default=True)
            except Address.DoesNotExist:
                default_addr=None


        print(content)
        return render(request,'place_order.html',{'goods':content,'addr':addr,'default_addr':default_addr})
class commit_order(View):
    @transaction.atomic
    def post(self,request):
        user=request.user
        try:
            save_id=transaction.savepoint()
            if user.is_authenticated:
                sku_ids=request.POST.getlist('sku_id[]')
                addr_id=request.POST.get('addr_id')
                pay_id=request.POST.get('pay_id')
                print(sku_ids,addr_id,pay_id)
                print(request.POST)
                
                order=OrderInfo()

                order.user=user
                try:
                    addr=Address.objects.get(id=addr_id)
                    order.addr=addr
                except Address.DoesNotExist:
                    transaction.savepoint_rollback(save_id)
                    return JsonResponse({'res':0,'errmsg':"地址编号错误"})
                if pay_id not in OrderInfo.PAY_METHODS.keys():
                    transaction.savepoint_rollback(save_id)
                    return JsonResponse({'res':0,'errmsg':"非法的支付方式"})
                order.pay_method=pay_id
                sku_goods=[]
                count=0
                total_cost=0
                user_key="cart_{}".format(user.id)
                try:
                    con=get_redis_connection('default')
                    for id in sku_ids:

                        s_g=GoodsSKU.objects.get(id=id)
                        num=con.hget(user_key,id)
                        price=s_g.price


                        #sku_goods.append(s_g)
                        count+=int(num.decode())
                        total_cost+=int(num.decode())*price
                except GoodsSKU.DoesNotExist:
                    transaction.savepoint_rollback(save_id)
                    return JsonResponse({'res':0,'errmsg':'商品不存在'})



                #except:
                #    return JsonResponse({'res':0,'errmsg':'商品库存不足'})
                order.total_count=count
                order.total_price=total_cost
                order.transit_price=10
                order_status=1
                order.order_id=datetime.now().strftime("%Y%m%d%H%M%S")+str(user)
                order.save()
                for id in sku_ids:
                    
                    for i in range(3):
                        s_g=GoodsSKU.objects.get(id=id)
                        a=OrderGoods()
                        num=con.hget(user_key,s_g.id)
                        price=s_g.price
                        ori_num=s_g.stock
                        print("user:{},ori_num{}".format(user.id,ori_num))
                        if int(num.decode())<=s_g.stock: 
                            a.order=order
                            a.sku=s_g
                            a.count=int(num.decode())
                            a.price=int(num.decode())*price

                            n=GoodsSKU.objects.filter(id=id,stock=ori_num).update(stock=ori_num-int(num.decode()),sales=s_g.sales+int(num.decode()))
                            if n==0:
                                if i==2:
                                    transaction.savepoint_rollback(save_id)
                                    return JsonResponse({'res':0,'errmsg':'商品库存不足1'})
                            else:
                                a.save()
                                break
                                
                            
                        else:
                            transaction.savepoint_rollback(save_id)
                            return JsonResponse({'res':0,'errmsg':'商品库存不足'})


                con.hdel(user_key,*sku_ids)
                transaction.savepoint_commit(save_id)
                return JsonResponse({'res':5})
        except:
            transaction.savepoint_rollback(save_id)
class pay_view(View):
    def post(self,request):
        if not request.user.is_authenticated:
            return JsonResponse({'res':0,'errmsg':"账号未登录"})
        order_id=request.POST.get('order_id')
        print(order_id)
        if not order_id:
            return JsonResponse({'res':0,'errmsg':"缺少订单编号"})
        try:
            order_=OrderInfo.objects.get(
                order_id=order_id,
                user=request.user,
                pay_method=3,
                
                order_status=1

            )
            print("订单存在")
        except OrderInfo.DoesNotExist:
            return JsonResponse({'res':0,'errmsg':"该订单不存在"})
        private_key_string=open(os.path.join(settings.BASE_DIR,'order/app_private_key.pem')).read()
        public_key_string=open(os.path.join(settings.BASE_DIR,'order/alipay_public_key.pem')).read()
        alipay_=AliPay(
            appid=2016102100732617,
            app_notify_url=None,
            app_private_key_string=private_key_string,
            alipay_public_key_string=public_key_string,
            debug=True,
            sign_type="RSA2"

        )
        print("alipay实例化成功")
        total_pay=order_.total_price+order_.transit_price
        order_string=alipay_.api_alipay_trade_page_pay(
            out_trade_no=str(order_id),  # 订单 id
            total_amount=str(total_pay),  # 支付总金额
            subject='天天生鲜%s' % order_id,
            return_url=None,
            notify_url=None  # 可以不填
        )
        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
        return JsonResponse({'res': 3, 'pay_url': pay_url})
class check_view(View):
    def post(self,request):
        if not request.user.is_authenticated:
            return JsonResponse({'res':0,'errmsg':"账号未登录"})
        order_id=request.POST.get('order_id')
        print(order_id)
        if not order_id:
            return JsonResponse({'res':0,'errmsg':"缺少订单编号"})
        try:
            order=OrderInfo.objects.get(
                order_id=order_id,
                user=request.user,
                pay_method=3,
                
                order_status=1

            )
            print("订单存在")
        except OrderInfo.DoesNotExist:
            return JsonResponse({'res':0,'errmsg':"该订单不存在"})
        private_key_string=open(os.path.join(settings.BASE_DIR,'order/app_private_key.pem')).read()
        public_key_string=open(os.path.join(settings.BASE_DIR,'order/alipay_public_key.pem')).read()
        alipay=AliPay(
            appid=2016102100732617,
            app_notify_url=None,
            app_private_key_string=private_key_string,
            alipay_public_key_string=public_key_string,
            debug=True,
            sign_type="RSA2"
        )
        while True:

            # 调用alipay工具查询支付结果
            response = alipay.api_alipay_trade_query(order_id)

            # 判断支付结果
            code = response.get('code')  # 支付宝接口调用成功或者错误的标志
            trade_status = response.get("trade_status")  # 用户支付的情况

            # 调用查询接成功口和商品交易成功
            if code == '10000' and trade_status == "TRADE_SUCCESS":
                # 支付成功
                # 获取支付宝交易号
                trade_no = response.get('trade_no')
                # 更新订单状态
                order.trade_no = trade_no
                order.order_status = 4  # 改成待评价状态
                order.save()
                # 返回结果
                return JsonResponse({'res': 3, 'message': '支付成功'})
            # 调用查询接口成功，但是等待买家去付款，并不代表用户支付没有成功，还需要等待一段时间
            elif code == "40004" or (code == "10000" and trade_status == "WAIT_BUYER_PAY"):
                # 等待买家付款
                import time
                time.sleep(5)  # 休眠5秒，把查询的地方放入一个循环，过5秒之后再调用一次，用户就可能支付成功了
                continue
            else:
                # 支付出错
                return JsonResponse({'res': 4, 'errmsg': '支付失败'})
class comment_view(View):
    def get(self,request,order_id):
        if request.user.is_authenticated:
            try:
                order=OrderInfo.objects.get(order_id=order_id)
            except OrderInfo.DoesNotExist:
                return redirect(reverse("goods:index"))
            goods=order.ordergoods_set.all()
            order.order_skus=goods
            return render(request,'comment_submit.html',{'order':order})
        else:
            return redirect(reverse("goods:index"))
    def post(self,request,order_id):
        if request.user.is_authenticated:
            total_count=request.POST.get('total_count',0)
            order_id=request.POST.get('order_id')

            try:
                total_count=int(total_count)
            except:
                return redirect(reverse("goods:index"))
            try:
                order=OrderInfo.objects.get(order_id=request.POST.get('order_id'))
            except OrderInfo.DoesNotExist:
                return redirect(reverse("goods:index"))
            for i in range(1,total_count+1):
                sku_id=request.POST.get("sku_{}".format(i))
                content=request.POST.get("content_{}".format(i))
                try:
                    good=OrderGoods.objects.get(order_id=order_id,sku_id=sku_id)
                    good.comment=content
                    good.save()
                except OrderGoods.DoesNotExist:
                    continue
            order.order_status=5
            order.save()
            return redirect(reverse("user:order"))
        return redirect(reveres("goods:index"))
            


        